﻿function AttendanceStatusController($scope, service, $routeParams, $location, $http) {
    //Date time picker
    $scope.openDayFrom = function ($event) {
        $event.preventDefault();
        $event.stopPropagation();

        $scope.openedDayForm = true;
    };

    $scope.openDayTo = function ($event) {
        $event.preventDefault();
        $event.stopPropagation();

        $scope.openedDayTo = true;
    };
    $scope.initDate = new Date('2016-15-20');
    $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
    $scope.format = $scope.formats[1];
    //End
    var date = new Date();
    //var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
    //var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
    $scope.dfrom = date;
    $scope.dto = date;
    $scope.caseOne = false;
    //calendar
    var calendarPicker2 = $("#dsel2").calendarPicker({
        monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
        dayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
        //useWheel:true,
        //callbackDelay:500,
        years: 2,
        months: 4,
        days: 5,
        showDayArrows: false,
        callback: function (cal) {
            $("#wtf").html("Selected date: " + cal.currentDate);
            $scope.calendarSelected = cal.currentDate;
            $scope.dfrom = $scope.calendarSelected;
            $scope.dto = $scope.calendarSelected;
            getDateFirstTime()
        }
    });
    //end
    //get data of Store list api/storelist/1
    $http.get(service.locationUrl + "/companystore/companyid/" + service.infoUser.Id, {})
        .success(function (data) {
            $scope.rowsStoreList = data;
            $scope.myStore = data[0].Name;
            getDateFirstTime();
        })
        .error(function (err) {

            console.log("error", err);
        });
    //End
    /// create data for csv type 1
    function dataCSV(data) {
        var dataBig = [];
        var arrayTitleCSV = ['Name', 'Id', 'ContractType', 'TotalWork', 'TotalBeark', 'TotalGoOut'];
        _.each(data, function (i) {
            _.each(arrayTitleCSV, function (j) {
                if (j == 'ContractType' && i[j] == 1) {
                    i[j] = 'Staff';
                    dataBig.push(i[j]);
                }
                else if (j == 'ContractType' && i[j] == 2) {
                    // dataBig.push('Contract Staff');
                    i[j] = 'Contract Staff';
                    dataBig.push(i[j]);
                }
                else if (j == 'ContractType' && i[j] == 3) {
                    //dataBig.push('Part staff');
                    i[j] = 'Part staff';
                    dataBig.push(i[j]);
                }
                else if (j == 'ContractType' && i[j] == 4) {
                    //dataBig.push('Part Time staff');
                    i[j] = 'Part Time staff';
                    dataBig.push(i[j]);
                }
                else {
                    if (j == 'Name' && dataBig.length >= 6) {
                        dataBig.push('\n' + i[j]);
                    }
                    else {
                        dataBig.push(i[j]);
                    }
                }



            })
        });
        return dataBig;
    }
    //end
    /// create data for csv type 2
    function dataType2CSV(data) {
        var dataBig = [];
        var arrayTitleCSV = ['Name', 'Id', 'ContractType', 'CheckIn', 'CheckOut', 'TotalWork', 'TotalBeark', 'TotalGoOut'];
        _.each(data, function (i) {
            _.each(arrayTitleCSV, function (j) {
                if (j == 'ContractType' && i[j] == 1) {
                    i[j] = 'Staff';
                    dataBig.push(i[j]);
                }
                else if (j == 'ContractType' && i[j] == 2) {
                    // dataBig.push('Contract Staff');
                    i[j] = 'Contract Staff';
                    dataBig.push(i[j]);
                }
                else if (j == 'ContractType' && i[j] == 3) {
                    //dataBig.push('Part staff');
                    i[j] = 'Part staff';
                    dataBig.push(i[j]);
                }
                else if (j == 'ContractType' && i[j] == 4) {
                    //dataBig.push('Part Time staff');
                    i[j] = 'Part Time staff';
                    dataBig.push(i[j]);
                }
                else {
                    if (j == 'Name' && dataBig.length >= 8) {
                        dataBig.push('\n' + i[j]);
                    }
                    else {
                        dataBig.push(i[j]);
                    }
                }



            })
        });
        return dataBig;
    }
    //end
    // create csv type 1
    function createCSV(data) {
        var csvText = " Staff name,Staff ID,Staff type, Total Work, Total break, Total go out" +
            "\n" +
            dataCSV(data);
        return csvText;
    }
    //end
    // create csv type2
    function createType2CSV(data) {
        var csvText = " Staff name,Staff ID,Staff type, Check In, Check Out, Total Work, Total break, Total go out" +
            "\n" +
            dataType2CSV(data);
        return csvText;
    }
    //end
    function getDateFirstTime(){
        /// get data of total of month 
        $http.get(service.locationUrl + "/totalworkofstaff/companyId/" + service.infoUser.Id + "/stampdate/" + $scope.dfrom.toString('yyyy-MMM-dd') + "/storeName/" + $scope.myStore, {})
            .success(function (data) {
                $scope.rowsAtdStatus = data;
                //export csv to download
                $scope.ExpCSV = function () {
                    // use for japan font
                    //var blob = new Blob(["\uFEFF", createCSV()], {});
                    var blob = new Blob([createType2CSV(data)], {});
                    //new way
                    var csvUrl = URL.createObjectURL(blob);
                    console.log("CSvurl", csvUrl);
                    $("#expCsv")
                                .attr({
                                    'download': "AttendanceStatus.csv",
                                    'href': csvUrl
                                });

                }
                //END
            })
            .error(function (err) {

                console.log("error", err);
            });
        //END
    }
    $scope.selectedEdit = function (id)
    {
        $location.path("/AttendanceList/" + id)
    }

    $scope.changeDate = function () {
        if ($scope.dfrom.toString('yyyy-MMM-dd') === $scope.dto.toString('yyyy-MMM-dd')) {
            /// get data of total of month 
            $http.get(service.locationUrl + "/totalworkofstaff/companyId/" + service.infoUser.Id + "/stampdate/" + $scope.dfrom.toString('yyyy-MMM-dd') + "/storeName/" + $scope.myStore, {})
                    .success(function (data) {
                        $scope.rowsAtdStatus = data;
                        $scope.caseOne = false;
                        //export csv to download
                        $scope.ExpCSV = function () {
                            // use for japan font
                            //var blob = new Blob(["\uFEFF", createCSV()], {});
                            var blob = new Blob([createType2CSV(data)], {});
                            //new way
                            var csvUrl = URL.createObjectURL(blob);
                            console.log("CSvurl", csvUrl);
                            $("#expCsv")
                                        .attr({
                                            'download': "AttendanceStatus.csv",
                                            'href': csvUrl
                                        });

                        }
                        //END
                })
                .error(function (err) {

                    console.log("error", err);
                });
            //END
        } else {
            //get data of attendace status
            $http.get(service.locationUrl + "/worktimeofstaffs/id/" + service.infoUser.Id + "/DateForm/" + $scope.dfrom.toString('yyyy-MMM-dd') + "/DateTo/" + $scope.dto.toString('yyyy-MMM-dd'), {})
               .success(function (data) {
                   $scope.rowsAtdStatus = data;
                   $scope.caseOne = true;
                   //export csv to download
                   $scope.ExpCSV = function () {
                       // use for japan font
                       //var blob = new Blob(["\uFEFF", createCSV()], {});
                       var blob = new Blob([createCSV(data)], {});
                       //new way
                       var csvUrl = URL.createObjectURL(blob);
                       console.log("CSvurl", csvUrl);

                       $("#expCsv")
                                   .attr({
                                       'download': "AttendanceStatus.csv",
                                       'href': csvUrl
                                   });

                   }
                   //END

               })
               .error(function (err) {

                   console.log("error", err);
               });
        }
    }

    $scope.update = function ()
    {
        if ($scope.myStore == "") {
            
        } else {
            if ($scope.dfrom.toString('yyyy-MMM-dd') === $scope.dto.toString('yyyy-MMM-dd')) {
                /// get data of total of month 
                $http.get(service.locationUrl + "/totalworkofstaff/companyId/" + service.infoUser.Id + "/stampdate/" + $scope.dfrom.toString('yyyy-MMM-dd') + "/storeName/" + $scope.myStore, {})
                        .success(function (data) {
                            $scope.rowsAtdStatus = data;
                            $scope.caseOne = false;
                            //export csv to download
                            $scope.ExpCSV = function () {
                                // use for japan font
                                //var blob = new Blob(["\uFEFF", createCSV()], {});
                                var blob = new Blob([createType2CSV(data)], {});
                                //new way
                                var csvUrl = URL.createObjectURL(blob);
                                console.log("CSvurl", csvUrl);
                                $("#expCsv")
                                            .attr({
                                                'download': "AttendanceStatus.csv",
                                                'href': csvUrl
                                            });

                            }
                            //END

                    })
                    .error(function (err) {

                        console.log("error", err);
                    });
                //END
            } else {
                $http.get(service.locationUrl + "/worktimeofstaffs/id/" + service.infoUser.Id + "/StoreName/" + $scope.myStore + "/DateForm/" + $scope.dfrom.toString('yyyy-MMM-dd') + "/DateTo/" + $scope.dto.toString('yyyy-MMM-dd'), {})
                   .success(function (data) {
                       $scope.rowsAtdStatus = data;
                       $scope.caseOne = true;
                       //export csv to download
                       $scope.ExpCSV = function () {
                           // use for japan font
                           //var blob = new Blob(["\uFEFF", createCSV()], {});
                           var blob = new Blob([createCSV(data)], {});
                           //new way
                           var csvUrl = URL.createObjectURL(blob);
                           console.log("CSvurl", csvUrl);

                           $("#expCsv")
                                       .attr({
                                           'download': "AttendanceStatus.csv",
                                           'href': csvUrl
                                       });

                       }
                       //END
                   })
                   .error(function (err) {

                       console.log("error", err);
                   });
            }
        }
    }
}

